package com.mustachio.urlshortener
{
	import com.mustachio.comp.SocialControlPanelToolTip2;
	import com.mustachio.urlshortener.events.LinkBoundCalculationEvent;
	import com.mustachio.urlshortener.events.LinkEvent;
	
	import flash.display.Sprite;
	import flash.events.*;
	import flash.geom.Point;
	import flash.text.TextField;
	
	import mx.collections.ArrayCollection;
	import mx.controls.TextArea;
	import mx.controls.textClasses.TextRange;
	import mx.managers.PopUpManager;
	
	public class LinkIdentifer extends Sprite
	{
		private var linkRegExp:RegExp;
			
		private var tr:TextRange;
			
		private var tmpArray:Array;
			
		private var linkObj:Object;
		
		private var dispatchFlag:Boolean = true;
		
		private var compareArray:Array = new Array();
			
		public var tmpLinkArray:ArrayCollection = new ArrayCollection();
		
		private var linkEvent:LinkEvent;
		
		public var ta:TextArea;
		
		public var ogLinkArray:ArrayCollection = new ArrayCollection();
		
		//NEW VARS USED FOR V2 
		
		public var linkObjectArray:ArrayCollection;
		
		private var matchArray:ArrayCollection;
		
		private var urlShortenService:URLShortenService;
		
		private var linkHighlighter:LinkHighlighter = new  LinkHighlighter();
		
		private var toolTipMaker:LinkToolTip;
		
		private var linkBoundsCalc:CalcLinkBounds;
		
		//END NEW VARIABLES USED IN V2
		
		//TESTING VARS
		
		private var localTextField:TextField;
		
		private var popUp:SocialControlPanelToolTip2;
		
		public function LinkIdentifer(_ta:TextArea)
		{
			//first we assign the incoming TextArea object
			//to a local TextArea object to reference in the
			//rest of the class.
			ta = _ta;
			localTextField = ta.getChildAt(2) as TextField;
			//add event listener for the key up on our text area we pass in
			ta.addEventListener(KeyboardEvent.KEY_UP, checkForURL, false, 0, true);
			ta.addEventListener(TextEvent.LINK, linkClickHandler, false, 0, true);
			
			
			//this array will hold the LinkVO objects that contain all our data;
			linkObjectArray = new ArrayCollection();
			
			//this is the array we assign the RegExp matches to.
			matchArray = new ArrayCollection();
			
			//this is the regualr expression to use
			linkRegExp = new RegExp();
			linkRegExp = /\b([\d\w\.\/\+\-\?\:]*)((ht|f)tp(s|)\:\/\/|[\d\d\d|\d\d]\.[\d\d\d|\d\d]\.|www\.|\.tv|\.ac|\.com|\.edu|\.gov|\.int|\.mil|\.net|\.org|\.biz|\.info|\.name|\.pro|\.museum|\.co)([\d\w\.\/\%\+\-\=\&\?\:\\\"\'\,\|\~\;]*)\b\s/g;
		
		}
		
		private function textHandler(e:TextEvent):void{
			
		}
		
		private function linkClickHandler(e:TextEvent):void{
			popUp = PopUpManager.createPopUp(ta, SocialControlPanelToolTip2, false) as SocialControlPanelToolTip2;
			popUp.closeBtn.addEventListener(MouseEvent.CLICK, removePopUp, false, 0, true);
			PopUpManager.bringToFront(popUp);
			for(var i:uint = 0; i <linkObjectArray.length; i++ ){
				if(e.text == linkObjectArray[i].fullLink || e.text == linkObjectArray[i].shortLink){
					popUp.addEventListener("undoEvent", undoHandler, false, 0, true);
					popUp.addEventListener("redoEvent", redoHandler, false, 0, true);
					popUp.fullLinkText.htmlText = "<a href='"+linkObjectArray[i].fullLink+"'>"+linkObjectArray[i].fullLink+"</a>";
					popUp.x = ta.x + linkObjectArray[i].linkXPosition;
					popUp.y = (ta.y - popUp.height) + linkObjectArray[i].linkYPosition;
				}
			}
			trace(globalToLocal(new Point(mouseX, mouseY)));
			trace(localToGlobal(new Point(mouseX, mouseY)));
			trace(mouseY);
		}
		
		private function removePopUp(e:MouseEvent):void{
			popUp.removeEventListener("undoEvent", undoHandler, false);
			popUp.removeEventListener("redoEvent", redoHandler, false);
			PopUpManager.removePopUp(popUp);
		}
		
		private function undoHandler(e:Event):void{
			for(var i:uint = 0; i < linkObjectArray.length; i++){
				if(e.target.fullLinkText.text == linkObjectArray[i].fullLink){
					ta.htmlText = ta.text.replace(linkObjectArray[i].shortLink, "<a href='event:"+linkObjectArray[i].fullLink+"'><u>"+linkObjectArray[i].fullLink+"</u></a>"); 
					e.target.fullLinkText.text = linkObjectArray[i].shortLink;
				}
			}
		}
		
		private function redoHandler(e:Event):void{
			for(var i:uint = 0; i < linkObjectArray.length; i++){
				if(e.target.fullLinkText.text == linkObjectArray[i].shortLink){
					ta.htmlText = ta.text.replace(linkObjectArray[i].fullLink, "<a href='event:"+linkObjectArray[i].shortLink+"'><u>"+linkObjectArray[i].shortLink+"</u></a>"); 
					e.target.fullLinkText.text = linkObjectArray[i].fullLink;
				}
			}
		}
		
		public function reset():void{
			//this clears out all the data from the array collections and arrays and resets
			//the dispatch flag to true;
			tmpLinkArray.removeAll();
			tmpArray = null;
			tmpArray = new Array();
			compareArray = null;
			compareArray = new Array();
			dispatchFlag = true;
		}
		
		public function checkForURL(e:KeyboardEvent):void{
			tmpArray = ta.text.match(linkRegExp);
			//this makes it run only if we have matches to our RegExp
			if(ta.text.match(linkRegExp).length !=  0){
				
				//this looks at the matchArray and compares it to the regexp return
				//array to see it they are differant. which we want.
				if(matchArray.length != ta.text.match(linkRegExp).length){
					//if the number in the regexp array = matchArray +1 that 
					//means we added one to the array.
					if(ta.text.match(linkRegExp).length == matchArray.length + 1 || matchArray.length == 1){
						trace("+1 Link");
						var linkVO:LinkVO = new LinkVO();
						linkVO.fullLink = tmpArray[tmpArray.length-1];
						linkVO.linkLength = tmpArray[tmpArray.length-1].length;
						linkVO.startingIndex = ta.text.indexOf(tmpArray[tmpArray.length-1]);
						//linkVO.shortLink = urlShortenService.shortURL;
						urlShortenService = new URLShortenService(tmpArray[tmpArray.length-1], linkVO);
						urlShortenService.addEventListener("URLShortenResponseEvent", shortenResponseHandler, false, 0, true);
					}
					//if the number is -1 than we took one out of the array
					if(ta.text.match(linkRegExp).length == matchArray.length -1 && matchArray.length != 0){
						trace("-1 Link");
						//trace(matchArray + " : MatchArray");
						for(var i:uint = 0; i < linkObjectArray.length; i++){
				
							for(var p:uint = 0; p < tmpArray.length; p++){
								trace(linkObjectArray[i].shortLink + tmpArray[p])
								if(tmpArray[p] == linkObjectArray[i].shortLink){
									trace("im here");
									trace(linkObjectArray[i].shortLink + tmpArray[p]);
								}
							}
						}
						linkObjectArray.removeItemAt(linkObjectArray.length - 1);
						matchArray.removeItemAt(matchArray.length - 1);
						trace(linkObjectArray + " : LinkArray");
					}
					
					//so if we do have a match or an array is returned
					//we assign its value to something we can use.
					matchArray.source = ta.text.match(linkRegExp);
				
				}
			}else if (matchArray.length == 1 || matchArray.length != 0){
				trace("- first link");
				if(linkObjectArray.length == 1){
					linkObjectArray.removeItemAt(0);
				}
				if(matchArray.length == 1){
					matchArray.removeItemAt(0);
				}
			}
		}
		
		private function shortenResponseHandler(e:LinkEvent):void{
				//need to figure out why this is not highlighting the text.
				ta.htmlText = ta.htmlText.replace(e.linkVO.fullLink, "<a href='event:"+e.linkVO.fullLink+"'><u>"+e.linkVO.shortLink+"</u></a>");
				//localTextField.replaceText(e.linkVO.startingIndex, e.linkVO.startingIndex + e.linkVO.linkLength, "<a href='event:"+e.linkVO.fullLink+"'><u>"+e.linkVO.shortLink+"</u></a>");
				//localTextField.htmlText = localTextField.text;
				linkHighlighter.highlightText(ta, e.linkVO.startingIndex, e.linkVO.startingIndex + 19);
				linkBoundsCalc = new CalcLinkBounds(ta, e.linkVO.startingIndex, e.linkVO);
				linkBoundsCalc.addEventListener("linkBoundCalculationEvent", linkCalculationHandler, false, 0, true);
				linkBoundsCalc.runCalculation();
				
				trace("Calc:");
		}
		
		private function linkCalculationHandler(e:LinkBoundCalculationEvent):void{
			//now that we have all the fields in our linkVO filled in we add it to the
			//ArrayCollection that is going to hold all the VO's
			linkObjectArray.addItem(e.linkVO);
		}
		
		private function makeToolTips(incomingLinkVO:LinkVO):void{
			//toolTipMaker = new LinkToolTip(incomingLinkVO.linkXPosition, incomingLinkVO.linkYPosition, incomingLinkVO.textLength, ta);
		}
			
			
		public function recheckURL():void{
			for(var i:uint = 0; i <linkObjectArray.length; i++ ){
				tr = new TextRange(ta, false, linkObjectArray[i].startingIndex,linkObjectArray[i].startingIndex + 19);
				tr.color = "#666666";
				tr.textDecoration = "underline";
			}
			
			
		}
			
			
			

	}
}